<?php

namespace app\admin\controller\xykeep;

use app\common\controller\Backend;
use fast\Tree;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;
use app\admin\model\xykeep\Coach;
use app\admin\model\xykeep\distribution\Level as DisLevelModel;
use Exception;
use think\Db;

/**
 * 课程管理
 *
 * @icon fa fa-circle-o
 */
class Course extends Backend
{

    /**
     * Course模型对象
     * @var \app\admin\model\xykeep\Course
     */
    protected $model = null;
    protected $categoryModel = null;
    protected $relationSearch = true;
    protected $searchFields = 'id,name,coach.nickname';

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xykeep\Course;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("isDisList", $this->model->getIsDisList());
        $this->view->assign("disRuleList", $this->model->getDisRuleList());

        $this->categoryModel = model('app\admin\model\xykeep\Category');

        $tree = Tree::instance();
        $tree->init(collection($this->categoryModel->where(['type'=>'course'])->order('id desc')->select())->toArray(), 'pid');
        $categoryList = $tree->getTreeList($tree->getTreeArray(0), 'name');
        foreach ($categoryList as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        //分销等级
        $disLevel = DisLevelModel::where(['status'=>'normal'])->select();
        $this->assignconfig('disLevel',$disLevel);
        $this->view->assign("categoryList", $categorydata);

    }

    /**
     * 复制
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function copy($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        $result = false;
        Db::startTrans();
        try {

            $result = $this->model->allowField(true)->save([
                'coach_id' => $row['coach_id'],
                'store_id' => $row['store_id'],
                'image' => $row['image'],
                'category_id' => $row['category_id'],
                'image' => $row['image'],
                'name' => $row['name'],
                'type' => $row['type'],
                'price' => $row['price'],
                'line_price' => $row['line_price'],
                'duration' => $row['duration'],
				'start_sale' => $row['start_sale'],
				'crowd' => $row['crowd'],
				'intro' => $row['intro'],
                'rule' => $row['rule'],
                'note' => $row['note'],
                'sales' => $row['sales'],
                'show_sales' => $row['show_sales'],
                'sales' => $row['sales'],
                'status' => 'hidden'
            ]);

            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['category','coach','store'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);
            
            unset($row);

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }

            $coach = Coach::where(['id'=>$params['coach_id']])->find();
            $params['store_id'] = $coach['store_id'];
            $result = $this->model->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->assignconfig('is_dis',$row['is_dis']);
            $this->assignconfig('dis_rule',$row['dis_rule']);
            $this->assignconfig('commission_rule',$row['commission_rule']);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                $row->validateFailException()->validate($validate);
            }
            $coach = Coach::where(['id'=>$params['coach_id']])->find();
            $params['store_id'] = $coach['store_id'];
            $result = $row->allowField(true)->save($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
	 * 选择
	 */
	public function select($coach_id = 0)
	{
	    if ($this->request->isAjax()) {
            [$where, $sort, $order, $offset, $limit] = $this->buildparams();
            $where1 = [];
            if($coach_id>0){
                $where1 = ['coach_id'=>$coach_id];
            }
            $list = $this->model
                ->with(['category','coach','store'])
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];
            return json($result);
	    }
        $this->assignconfig('coach_id',$coach_id);
	    return $this->view->fetch();
	}

}
